import { Input } from 'antd';
import { useEffect, useState } from 'react';
import { useNavigate, useLocation, useSearchParams } from 'react-router-dom';
import { LIST_SEARCH_KEY } from '../constant';
const { Search } = Input;

const ListSearch = () => {
	const nav = useNavigate();
	const { pathname } = useLocation();
	const [searchValue, setSearchValue] = useState('');
	const [searchParams] = useSearchParams();

	const changeSearch = e => {
		setSearchValue(e.target.value);
		console.log(searchValue);
	};
	const handlerSearch = () => {
		console.log(searchValue, 'searchValue');
		nav({
			pathname,
			search: `${LIST_SEARCH_KEY}=${searchValue}`,
		});
	};
	// 如果url搜索值变了,同步到搜索框中
	useEffect(() => {
		const newVal = searchParams.get(LIST_SEARCH_KEY) || '';
		setSearchValue(newVal);
	}, [searchParams]);
	return (
		<div>
			<Search
				allowClear
				placeholder="请输入搜索"
				value={searchValue}
				onChange={changeSearch}
				onSearch={handlerSearch}
				style={{ width: '300px' }}
			/>
		</div>
	);
};

export default ListSearch;
